package com.hn.common.utils;

import cn.hutool.core.util.StrUtil;
import com.hn.common.exception.LoginException;
import org.omg.PortableInterceptor.INACTIVE;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Struct;

/**
 * @author shilvfei
 */
public class SecurityUtils {

    private static final String USER_ID = "userId";

    public static final String TOKEN = "token";

    /**
     * 校区ID
     */
    public static final String CAMPUS_ID= "x-campusid";

    /**
     * 学段ID
     */
    public static final String PERIOD_ID = "x-periodId";

    /**
     * 获取userId
     */
    public static Integer getUserId() {
        String userId = getAttribute(USER_ID);
        if (userId == null) {
            throw new LoginException("登录已失效,请重新登录");
        }
        return Integer.valueOf(userId);
    }

    /**
     * 设置userId
     */
    public static Integer setUserId(Integer userId) {
        setAttribute(USER_ID, userId);
        return userId;
    }

    public static String getAttribute(String key) {
        Object o = getRequest().getAttribute(key);
        return null == o ? null : String.valueOf(o);
    }

    public static String getHeader(String key){
        return getRequest().getHeader(key);
    }

    public static void setAttribute(String key, Object value) {
        getRequest().setAttribute(key, value);
    }

    public static void removeAttribute(String key) {
        getRequest().removeAttribute(key);
    }

    public static HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    public static HttpServletResponse getResponse() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
    }

    public static String getToken() {
        return getHeader(TOKEN);
    }
}
